package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.CalendarAdapter;
import flc.ast.bean.MyCalendarBean;
import flc.ast.bean.PracticeTime;
import flc.ast.databinding.ActivityPracticeReportBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.PracticeDatabase;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.SPUtil;

public class PracticeReportActivity extends BaseAc<ActivityPracticeReportBinding> {

    private SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
    private CalendarAdapter calendarAdapter;
    private int oldPosition = 0;
    private int year, month, day, thisYear, thisMonth;

    @Override
    protected int onCreate() {
        return R.layout.activity_practice_report;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        mDataBinding.ivPracticeReportBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivLastMonth.setOnClickListener(this);
        mDataBinding.ivNextMonth.setOnClickListener(this);
        //日历
        mDataBinding.rvCalendarList.setLayoutManager(new GridLayoutManager(mContext, 7));
        calendarAdapter = new CalendarAdapter();
        mDataBinding.rvCalendarList.setAdapter(calendarAdapter);
        calendarAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivLastMonth://上一月
                if (month == 1) {
                    month = 12;
                    year--;
                } else {
                    month--;
                }
                if (month < 10) {
                    mDataBinding.tvDate.setText(year + ".0" + month);
                } else {
                    mDataBinding.tvDate.setText(year + "." + month);
                }
                setDay(month, year, false);
                if (month == 12) {
                    getMonthReport(year + "." + month + ".01", (year + 1) + ".01.01");
                } else {
                    getMonthReport(year + "." + month + ".01", year + "." + (month + 1) + ".01");
                }
                //显示标记
                showRecord();
                break;
            case R.id.ivNextMonth://下一月
                if (month == 12) {
                    month = 1;
                    year++;
                } else {
                    month++;
                }
                if (month < 10) {
                    mDataBinding.tvDate.setText(year + ".0" + month);
                } else {
                    mDataBinding.tvDate.setText(year + "." + month);
                }
                setDay(month, year, false);
                if (month == 12) {
                    getMonthReport(year + "." + month + ".01", (year + 1) + ".01.01");
                } else {
                    getMonthReport(year + "." + month + ".01", year + "." + (month + 1) + ".01");
                }
                //显示标记
                showRecord();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        calendarAdapter.getItem(oldPosition).setSelect(false);
        calendarAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        calendarAdapter.getItem(position).setSelect(true);
        calendarAdapter.notifyItemChanged(position);
        getTodayReport(year + "." + month + "." + calendarAdapter.getItem(position).getDate());
//        int selDay = Integer.parseInt(calendarAdapter.getItem(position).getDate());
//        String dayStr = "";
//        if (selDay < 10) {
//            dayStr += "0" + selDay;
//        } else {
//            dayStr += +selDay;
//        }

    }

    @Override
    protected void initData() {
        mDataBinding.tvDate.setText(TimeUtils.getNowString(new SimpleDateFormat("yyyy.MM")));//当前年月
        year = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("yyyy")));//获取当前年份
        month = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("M")));//获取当前月份
        day = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("d")));//获取当前天数
        setDay(month, year, true);//设置日历
        //默认选中显示今天的日期记录
        thisYear = year;
        thisMonth = month;
        getTodayReport(thisYear + "." + thisMonth + "." + day);
        if (month == 12) {
            getMonthReport(thisYear + "." + thisMonth + ".01", (thisYear + 1) + ".01.01");
        } else {
            getMonthReport(thisYear + "." + thisMonth + ".01", thisYear + "." + (thisMonth + 1) + ".01");
        }
        //显示标记
        showRecord();
    }

    //显示今天
    private void setShowNowDay(String date, boolean isFirst) {
        for (MyCalendarBean bean : calendarAdapter.getData()) {
            if (!TextUtils.isEmpty(bean.getDate())) {
                String nowDate = date + bean.getDate();
                Log.e("TAG", "setShowNowDay: " + nowDate);
                if (nowDate.equals(TimeUtils.getNowString(new SimpleDateFormat("yyyy.M.d")))) {
                    oldPosition = bean.getPos();
                    Log.e("TAG", "ShowNowDay: " + TimeUtils.getNowString(new SimpleDateFormat("yyyy.M.d")));
                    if (isFirst) {
                        bean.setSelect(true);
                    }
                    bean.setToday(true);
                    break;
                }
            }
        }
        calendarAdapter.notifyDataSetChanged();
    }

    //设置日期数据
    private void setDay(int month, int year, boolean isFirst) {
        //获取天数
        int dayNum = getDayNum(month);
        //获取需要空出的天数
        int weekNum = getWeekNum(month, year);
        //获取农历偏移量
        //生成日历表
        List<MyCalendarBean> listDay = new ArrayList<>();
        for (int i = 0; i < 42; i++) {
            if (i <= weekNum || i > dayNum + weekNum) {
                listDay.add(new MyCalendarBean("", i, false, false, false));//空
            } else {
                listDay.add(new MyCalendarBean(i - weekNum + "", i, false, false, false));
            }
        }
        calendarAdapter.setList(listDay);
        setShowNowDay(year + "." + month + ".", isFirst);
    }

    //判断该月有多少天
    private int getDayNum(int month) {
        int dayNum = 31;
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
            //大月31天
            dayNum = 31;
        } else if (month == 2) {
            //2月判断是闰(29)还是平(28)
            if (TimeUtils.isLeapYear(TimeUtils.getNowString(format), format)) {
                dayNum = 29;
            } else {
                dayNum = 28;
            }
        } else {
            //小月30天
            dayNum = 30;
        }
        return dayNum;
    }

    //获取该月第一天是星期几（当天要算上 所以少减一天）
    private int getWeekNum(int month, int year) {
        int weekNum = 0;
        String week = TimeUtils.getChineseWeek(year + "." + month + ".01", format);
        if (week.equals(getString(R.string.monday_text))) {
            weekNum = 0;
        } else if (week.equals(getString(R.string.tuesday_text))) {
            weekNum = 1;
        } else if (week.equals(getString(R.string.wednesday_text))) {
            weekNum = 2;
        } else if (week.equals(getString(R.string.thursday_text))) {
            weekNum = 3;
        } else if (week.equals(getString(R.string.friday_text))) {
            weekNum = 4;
        } else if (week.equals(getString(R.string.saturday_text))) {
            weekNum = 5;
        } else if (week.equals(getString(R.string.sunday_text))) {
            weekNum = 6;
        }
        return weekNum;
    }

    private void getTodayReport(String toDay) {
        //今日练琴时长
        long today = TimeUtils.string2Millis(toDay, new SimpleDateFormat("yyyy.MM.dd"));
//        Log.e("TAG", "getTodayReport: " + today);
        List<PracticeTime> todayPractice = PracticeDatabase.getInstance(mContext).getPracticeDao().getTodayPracticeTime(today);
        if (todayPractice.size() == 0) {
            mDataBinding.tvPracticeToday.setText("00:00:00");
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
            dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
            mDataBinding.tvPracticeToday.setText(TimeUtils.millis2String(todayPractice.get(0).getDuration(), dateFormat));
        }
    }

    private void getMonthReport(String startDate, String endDate) {
        long startTime = TimeUtils.string2Millis(startDate, new SimpleDateFormat("yyyy.MM.dd"));
        long endTime = TimeUtils.string2Millis(endDate, new SimpleDateFormat("yyyy.MM.dd"));
        //月练琴时长
        int count = 0;
        long duration = 0;
//        Log.e("TAG", "startTime: " + startTime);
//        Log.e("TAG", "endTime: " + endTime);
        List<PracticeTime> weekPractice = PracticeDatabase.getInstance(mContext).getPracticeDao().getMonthPracticeTime(startTime, endTime);

        if (weekPractice.size() == 0) {
            mDataBinding.tvPracticeNum.setText("0");
            mDataBinding.tvPracticeTime.setText("00:00:00");
        } else {
            for (PracticeTime practiceTime : weekPractice) {
                count += practiceTime.getCount();
                duration += practiceTime.getDuration();
            }
            mDataBinding.tvPracticeNum.setText(count + "");
            SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
            dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
            mDataBinding.tvPracticeTime.setText(TimeUtils.millis2String(duration, dateFormat));
        }
    }

    //显示标记
    private void showRecord() {
        for (MyCalendarBean bean : calendarAdapter.getValidData()) {
            bean.setRecord(false);
        }
        String date = year + "." + month;
        List<String> listSp = AppSpUtils.getPracticeList();
        if (listSp != null && listSp.size() > 0) {
            for (String s : listSp) {
                for (MyCalendarBean dayBean : calendarAdapter.getValidData()) {
                    long millis1 = TimeUtils.string2Millis(s, new SimpleDateFormat("yyyy.MM.dd"));
                    long millis2 = TimeUtils.string2Millis(date + "." + dayBean.getDate(), new SimpleDateFormat("yyyy.MM.dd"));
                    if (millis1 == millis2) {
                        dayBean.setRecord(true);
                    }
                }
            }
        }
        calendarAdapter.notifyDataSetChanged();
    }

}